package cn.shengchao.examstar.pay.model.service.fy.request;

import cn.shengchao.examstar.pay.model.service.fy.ParamName;
import cn.shengchao.examstar.pay.model.service.fy.dto.ParameterCollection;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public abstract class BaseFuYouRequest {

    public ParameterCollection toParameterCollection() {
        ParameterCollection collection = new ParameterCollection();
        Class<?> currentClass = this.getClass();
        List<Field> allFields = new ArrayList<>();

        while (currentClass != null && currentClass != Object.class) {
            allFields.addAll(Arrays.asList(currentClass.getDeclaredFields()));
            currentClass = currentClass.getSuperclass();
        }

        allFields.sort(Comparator.comparing(Field::getName));

        for (Field field : allFields) {
            if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
                continue; // Skip static or transient fields
            }
            field.setAccessible(true);
            ParamName paramNameAnnotation = field.getAnnotation(ParamName.class);
            String paramName = paramNameAnnotation != null ? paramNameAnnotation.value() : field.getName();

            try {
                Object value = field.get(this);
                collection.add(paramName, value != null ? String.valueOf(value) : null);
            } catch (IllegalAccessException e) {
                System.err.println("Error accessing field " + paramName + " in " + this.getClass().getSimpleName() + ": " + e.getMessage());
            }
        }
        return collection;
    }
}